const Router = require('@koa/router')
const mongoose = require('mongoose')
// const { getBody } = require('../utils/getBody')
const config = require('../project.config.js')
const { verify, getToken } = require('../utils/token')
const User = mongoose.model('Auth')
const Character = mongoose.model('Character')
const { loadExcel, getFirstSheet } = require('../utils/excel')
const router = new Router({
    prefix: '/user'
})

// http://localhost:3000/user/list
//获取用户列表  根据用户名keyword进行查找
router.get('/list', async (ctx) => {
    let {
        page,
        size,
        keyword
    } = ctx.query
    page = Number(page)
    size = Number(size)

    // const query = {}
    // if (keyword) {
    //     query.username = keyword
    // }
    let reg = new RegExp(keyword, "gim")
    const list = await User
        .find({ "username": { $regex: reg } })
        .sort({ _id: -1 }) //-1倒序
        .skip((page - 1) * size)
        .limit(size).exec()

    const total = await User.countDocuments().exec()
    ctx.body = {
        msg: '获取用户列表成功',
        data: {
            list,
            page,
            size,
            total
        },
        code: 200
    }
})
//删除操作 接口
router.delete('/:id', async (ctx) => {
    const {
        id
    } = ctx.params
    const delMsg = await User.deleteOne({
        _id: id
    })
    ctx.body = {
        data: delMsg,
        code: 200,
        msg: '删除成功'
    }
})
//添加用户接口
router.post('/add', async (ctx) => {
    const {
        username,
        password,
        character
        // password = 'root' //这种方式设不了默认值 只有为null undefined时才有效
    } = ctx.request.body
    const char = await Character.find({
        _id: character
    })
    if (!char) {
        ctx.body = {
            msg: '角色出错',
            code: 200
        }
        return
    }
    const user = new User({
        username,
        password: password || 'root',//设置默认值方式
        character
    })
    const res = await user.save()
    ctx.body = {
        data: res,
        code: 200,
        msg: '添加成功'
    }
})

//重置密码接口
router.post('/reset/password', async (ctx) => {
    const {
        id
    } = ctx.request.body
    const user = await User.findOne({
        _id: id
    }).exec()

    if (!user) {
        ctx.body = {
            msg: '找不到用户',
            code: 0
        }
        return
    }
    //设置重置 默认密码
    user.password = config.DEFAULT_PASSWORD
    await user.save()
    ctx.body = {
        msg: '重置密码成功',
        data: {
            account: user.account,
            _id: user._id
        },
        code: 200
    }
})
//修改角色
router.post('/updatecharacter', async (ctx) => {
    //要修改角色的id  要修改用户的id
    const {
        character,
        userId
    } = ctx.request.body
    //角色是否存在
    const char = await Character.findOne({
        _id: character
    })
    if (!char) {
        ctx.body = {
            msg: '角色不存在',
            code: 0
        }
        return
    }

    const user = await User.findOne({
        _id: userId
    })
    if (!user) {
        ctx.body = {
            msg: '用户不存在',
            code: 0
        }
        return
    }
    user.character = character
    const res = await user.save()
    ctx.body = {
        data: res,
        code: 200,
        msg: '修改角色成功'
    }
})

//通过token获取用户信息
router.get('/info', async (ctx) => {
    ctx.body = {
        data: await verify(getToken(ctx)),
        code: 200,
        msg: '获取token成功'
    }
})
//用户批量上传
router.post('/addMany', async (ctx) => {
    const {
        key = '',
    } = ctx.request.body;

    const path = `${config.UPLOAD_DIR}/${key}`;//根据前端参数拼接文件路径
    const excel = loadExcel(path);//解析excel
    const sheet = getFirstSheet(excel);

    const character = await Character.find().exec();
    // console.log(character);

    const member = character.find((item) => (item.name === 'member'));

    const arr = [];
    for (let i = 0; i < sheet.length; i++) {
        let record = sheet[i];
        const [username, password = config.DEFAULT_PASSWORD] = record;
        const one = await User.findOne({
            username,
        })
        if (one) {
            continue;
        }
        arr.push({
            username,
            password,
            character: member._id,//批量上传默认普通成员
        });
    }
    console.log(arr);
    const res = await User.insertMany(arr);
    console.log('res', res);
    ctx.body = {
        code: 200,
        msg: "批量添加成功！",
        data: {
            addCount: arr.length,
        },
    };
});
module.exports = router